package web.file;

import bean.File;
import bean.Union;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.FileEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "FileList",urlPatterns = "/dao/fileList")
public class FileList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String jsonString = FANREN.getJson(request);
        Union union = JSON.parseObject(jsonString,Union.class);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query;
        if(union.getSearch().equals("")){
            query = em.createQuery("select f from FileEntity f");
        } else {
            query = em.createQuery("select f from FileEntity f where f.name like '%" + union.getSearch() + "%'");
        }
        List<FileEntity> list = query.getResultList();

        int totalPage = list.size();

        int pos = (union.getCurrentPage() - 1) * 8;

        List<File> fileList = new ArrayList<>();
        for (int i=0,j=pos; i<8&&j<list.size(); i++,j++) {
            File file = new File(""+list.get(j).getFid(),list.get(j).getName(),list.get(j).getSize(),list.get(j).getMid().getName(),list.get(j).getTime());
            fileList.add(file);
        }

        String returnString = "{\"tableData\":" + JSON.toJSONString(fileList) +",\"totalPage\":" + totalPage + "}";
        response.getWriter().write(URLEncoder.encode(returnString,StandardCharsets.UTF_8));
    }
}
